#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <errno.h>
#include <pthread.h>
#define MAX_BUF 1024
#define SERVER_PORT 8888

// 接收消息线程
void *recv_msg(void *arg)
{
    sleep(1); // 延时，保证服务器先启动
    int client_fd = *(int *)arg;
    char recv_buf[MAX_BUF];
    int ret;
    while (1)
    {
        memset(recv_buf, 0, sizeof(recv_buf));
        ret = recv(client_fd, recv_buf, sizeof(recv_buf), 0);
        if (ret < 0)
        {
            perror("recv");
            continue;
        }
        if (ret == 0)
        {
            printf("server closed\n");
            break;
        }
        printf("recv from server: %s\n", recv_buf);
        sleep(3);
    }
    pthread_exit(NULL);
}

int main()
{

    int client_fd, server_fd;
    struct sockaddr_in server_addr;
    char send_buf[MAX_BUF];
    int ret, read_size;
    pthread_t tid;
    // 创建套接字
    client_fd = socket(AF_INET, SOCK_STREAM, 0); // IPV4 TCP
    if (client_fd < 0)
    {
        perror("socket");
        exit(1);
    }

    // 初始化服务器地址结构体
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(SERVER_PORT);
    server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    // 连接服务器
    ret = connect(client_fd, (struct sockaddr *)&server_addr, sizeof(server_addr));
    if (ret < 0)
    {
        perror("connect");
        close(client_fd);
        exit(1);
    }
    // 创建子线程接受数据
    ret = pthread_create(&tid, NULL, recv_msg, &client_fd);
    if (ret < 0)
    {
        perror("pthread_create");
        close(client_fd);
        exit(1);
    }

    // 发送数据
    while (1)
    {
        printf("请输入要发送的数据：\n");
        read_size = read(0, send_buf, sizeof(send_buf));
        if (read_size <= 0)
        {
            perror("read");
            continue;
        }
        // 结束符
        send_buf[read_size - 1] = '\0';
        if (strcmp(send_buf, "quit") == 0)
        {
            printf("退出\n");
            break;
        }

        // 发送数据
        ret = send(client_fd, send_buf, read_size, 0);
        if (ret < 0)
        {
            perror("send");
            continue;
        }
    }

    close(client_fd); // 关闭套接字

    return 0;
}